package com.zztl.infiniteBand.ui.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.provider.Settings
import android.support.v4.app.NotificationManagerCompat
import android.view.View
import butterknife.OnClick
import com.clj.fastble.BleManager
import com.tencent.bugly.beta.Beta

import com.zztl.infiniteBand.BraceletApplication
import com.zztl.infiniteBand.R
import com.zztl.infiniteBand.base.BaseMvpActivity
import com.zztl.infiniteBand.eventbus.FirmwareUpdateEvent
import com.zztl.infiniteBand.eventbus.LanguageEvent
import com.zztl.infiniteBand.model.ContactInfoBean
import com.zztl.infiniteBand.model.FirmwareVersionBean
import com.zztl.infiniteBand.model.VersionResponseBean
import com.zztl.infiniteBand.presenter.SyncStepPresenter
import com.zztl.infiniteBand.storage.BillPreference
import com.zztl.infiniteBand.storage.Constans
import com.zztl.infiniteBand.storage.PreferenceKeys
import com.zztl.infiniteBand.ui.view.dialog.ExitDialog
import com.zztl.infiniteBand.ui.view.mvpview.ContactInfoView
import com.zztl.infiniteBand.util.*
import kotlinx.android.synthetic.main.activity_setting.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class SettingActivity : BaseMvpActivity<ContactInfoView, SyncStepPresenter>(), ContactInfoView {


    private val NOTIFY_REQUEST_CONDE = 1
    private lateinit var mPresenter: SyncStepPresenter
    private var hasUpgrade: Boolean = false
    private var downUrl: String? = null
    private var version: String? = null


    override fun setLayoutId(): Int = R.layout.activity_setting


    companion object {
        /* fun reStart(context: Context) {
             val intent = Intent(context, SettingActivity::class.java).apply {
                 flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
             }
             context.startActivity(intent)
         }*/
        val LANGUAGE_CODE = 100
    }

    override fun initBase() {
        setTitle(getString(R.string.设置))
        hasUpgrade = intent.getBooleanExtra("upgrade", false).apply {
            if (this) {
                iv_update.visibility = View.VISIBLE
                downUrl = intent.getStringExtra("downUrl")
            }
        }

        /*   if (!hasUpgrade) {
               BraceletApplication.zhBraceletService?.addSimplePerformerListenerLis(mPerformerListener)
               mPresenter.getFirmwareVersion(FirmwareVersionRequest("hhh"), this)
           }
   */

        item_version!!.rightTextStr = "V" + AppInfoUtils.appVersionName
        checkbox.isChecked = BillPreference.getApp(PreferenceKeys.SMSTOGGLE.name, false) as Boolean
        checkbox.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                if (!isNotificationServiceEnable()) {
                    openNotificationListenSettings()
                    checkbox.isChecked = false
                } else {
                    PermissionUtils.requestMultiPermissions(this@SettingActivity, mPermissionGrant, PermissionUtils.CODE_SMS)
                }

            } else {
                BillPreference.putApp(PreferenceKeys.SMSTOGGLE.name, false)
            }

        }
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
                                            grantResults: IntArray) {
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant)

    }


    private val mPermissionGrant = object : PermissionUtils.PermissionGrant {
        override fun onPermissionGranted(requestCode: Int) {
            if (requestCode != PermissionUtils.CODE_MULTI_PERMISSION) {
                checkbox.isChecked = false
            } else {
                BillPreference.putApp(PreferenceKeys.SMSTOGGLE.name, true)
            }
        }

    }


    @OnClick(R.id.item_version, R.id.btn_exit_login, R.id.item_about, R.id.item_contact, R.id.item_amend_pwd, R.id.item_amend_pay_pwd,
            R.id.item_firmware_update, R.id.item_language)
    fun click(view: View) {
        when (view.id) {
            R.id.item_version -> mPresenter.getVersion(this)
            R.id.btn_exit_login -> showExitDialog(1)
            R.id.item_about -> showActivity(this, AboutUsActivity::class.java)
            R.id.item_contact -> {
                val intent = Intent(this, ContactUsActivity::class.java)
                showActivity(intent)
            }
            R.id.item_amend_pwd -> {
                val intent1 = Intent(this, ForgetOrResetPwdActivity::class.java)
                intent1.putExtra(Constans.ACTIVITY_FROM, "reset")
                showActivity(intent1)
            }
            R.id.item_amend_pay_pwd ->
                showActivity(this, VerifyPhoneActivity::class.java)
            R.id.item_firmware_update -> {
                BleManager.getInstance().isConnected.let {
                    if (it) {
                        downUrl ?: kotlin.run {
                            toast(getString(R.string.请检查网络))
                            return
                        }
                        if (hasUpgrade) {
                            showActivity(Intent(this, FirmwareUpdateActivity::class.java).apply {
                                putExtra("downUrl", downUrl)
                            })

                        } else {
                            toast(getString(R.string.当前已是最新版本))
                        }
                    } else {
                        toast(getString(R.string.未连接设备))
                    }
                }
            }
            R.id.item_language -> {
                showActivityForResult(this, SettingLanguageActivity::class.java, LANGUAGE_CODE)
            }

        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == LANGUAGE_CODE && resultCode == Activity.RESULT_OK) {
            onRestart()
            MainActivity.reStart(this)
//            EventBus.getDefault().post(LanguageEvent())
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    private fun showExitDialog(type: Int) {
        val msg: String = if (type == 1) getString(R.string.是否退出登录) else getString(R.string.是否恢复手环出厂设置)

        ExitDialog.Builder(this).setMessage(msg)
                .setClickListener(object : ExitDialog.Builder.ClickListener {
                    override fun cancel() {

                    }

                    override fun comfirm() {
                        if (type == 1) {
                            ActivityManager.getInstance().finishAllActivities()
                            BillPreference.putApp(PreferenceKeys.LOGINED.name, false)
                            BleManager.getInstance().isConnected.let {
                                if (it) {
                                    BleManager.getInstance().disconnectAllDevice()
                                }
                            }
                            BillPreference.putApp(PreferenceKeys.COUNTYRCODE.name, "86")
                            BraceletApplication.watchCountStep = 0;
                            skipActivity(this@SettingActivity, LoginActivity::class.java)
                        }
                    }
                }).create().let { it.show() }
    }


    fun openNotificationListenSettings() {
        try {
            val intent: Intent
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
                intent = Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
            } else {
                intent = Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")
            }
            showActivityForResult(intent, NOTIFY_REQUEST_CONDE)
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    private fun isNotificationServiceEnable(): Boolean {
        return NotificationManagerCompat.getEnabledListenerPackages(this).contains(packageName)
    }


    override fun createPresenter(): SyncStepPresenter {
        mPresenter = SyncStepPresenter()
        return mPresenter
    }

    override fun getSuccess(bean: ContactInfoBean) {

    }


    override fun update(bean: VersionResponseBean) {
        if (bean.data!!.version > AppInfoUtils.appVersionCode) {
            Beta.checkUpgrade()
        }else{
            toast(getString(R.string.已经是最新版本))
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun Event(event: FirmwareUpdateEvent) {
        hasUpgrade = false
        iv_update.visibility = View.GONE
    }

    override fun getVersion(bean: FirmwareVersionBean) {

    }

    override fun onDestroy() {
        super.onDestroy()
    }

}
